<template>
  <page-header-wrapper>
    <a-card>
      <a-row align="middle">
        <a-space class="table-operator">
          <a-button
            type="primary"
            style="margin-bottom: 0px;"
            @click="onEdit({})"
            icon="plus">
            新建
          </a-button>
        </a-space>
      </a-row>
      <s-table
        ref="tableList"
        size="default"
        row-key="id"
        :columns="columns"
        :data="loadData"
      >
        <template slot="template" slot-scope="template">
          <a-row type="flex" align="middle">
            <a-space>
              {{ template.name }}（{{ template.id }}）
            </a-space>
          </a-row>
        </template>
        <template slot="addtime" slot-scope="addtime">
          <a-row type="flex" align="middle">
            <a-space>
              {{ addtime | timeFormat }}
            </a-space>
          </a-row>
        </template>
        <a-switch
          slot="is_index"
          checked-children="开启"
          un-checked-children="关闭"
          slot-scope="is_index, page"
          :default-checked="is_index > 0"
          @change="onConfirmStatus('is_index', page.id)" />
        <a-switch
          slot="status"
          checked-children="开启"
          un-checked-children="关闭"
          slot-scope="status, page"
          :default-checked="status > 0"
          @change="onConfirmStatus('status', page.id)" />
        <a-space slot="action" slot-scope="text, page">
          <a-button size="small" title="编辑" @click="onEdit(page)">编辑</a-button>
          <a-button size="small" title="删除" @click="onDelete(page.id)">删除</a-button>
        </a-space>
      </s-table>
    </a-card>
    <a-drawer
      title="编辑页面"
      :width="720"
      @close="onClose"
      :destroyOnClose="true"
      :visible="visible">
      <template>
        <a-form
          action=""
          method="post"
          @submit="onSave"
          :form="form">
          <a-form-item :hidden="true" >
            <a-input
              v-decorator="['id']"
              type="number"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="页面名称" hasFeedback >
            <a-input
              placeholder="填写商户名称"
              v-decorator="['title', { rules: [ { required: true, message: '填写页面名称' } ] }]"
              type="text"
              :step="1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="选择模板" hasFeedback >
            <a-select
              v-if="template_list.length > 0"
              placeholder="请选择模板"
              v-decorator="['template_id', { rules: [ { required: true, message: '请选择模板' } ] }]">
              <a-select-option v-for="template in template_list" :key="template.id + ''">
                {{ template.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :gutter="[16,30]" type="flex" align="middle">
            <a-col offset="4">
              <a-button type="primary" html-type="submit">
                保存
              </a-button>
            </a-col>
          </a-form-item>
        </a-form>
      </template>
    </a-drawer>
  </page-header-wrapper>
</template>

<script>
import { pageList, pageSave, upDown, pageDel } from '@/api/diy'
import { STable } from '@/components'
import pick from 'lodash.pick'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '名称',
    dataIndex: 'title',
    scopedSlots: { customRender: 'title' }
  },
  {
    title: '模板名称',
    dataIndex: 'template',
    scopedSlots: { customRender: 'template' }
  },
  {
    title: '创建时间',
    dataIndex: 'addtime',
    scopedSlots: { customRender: 'addtime' }
  },
  {
    title: '是否设置首页',
    dataIndex: 'is_index',
    scopedSlots: { customRender: 'is_index' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'DiyPageList',
  components: {
    STable
  },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      columns: columns,
      visible: false,
      form: this.$form.createForm(this),
      pageInfo: {},
      addressInfo: {},
      template_list: [],
      loadData: parameter => {
        var that = this
        return pageList(parameter)
          .then(res => {
            that.template_list = res.template_list
            return res.data
          })
      }
    }
  },
  activated () {
    this.$refs.tableList.$data.localDataSource = []
    this.$refs.tableList.refresh(false)
  },
  created () {},
  methods: {
    refresh (row) {
      this.$nextTick(() => {
        this.$refs.tableList.$data.localDataSource = []
        this.$refs.tableList.refresh(true)
      })
    },
    onEdit (page) {
      this.visible = true
      this.pageInfo = page
      this.updateData()
    },
     /**
     * 渲染form表单
     */
    updateData () {
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.pageInfo, ['id', 'title', 'template_id']))
      })
    },
    onClose () {
      this.visible = false
      this.pageInfo = {}
    },
    onSave (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$message.loading({ content: '提交中', key: 'updatable' })
          pageSave(values).then(res => {
            if (res.code === 0) {
              this.$message.success({ content: res.msg, key: 'updatable' })
              this.$nextTick(() => {
                this.refresh()
                this.visible = false
              })
            } else {
              this.$message.error({ content: res.msg, key: 'updatable' })
            }
          })
        } else {
          for (const key in err) {
            this.$message.error(err[key].errors[0].message)
          }
        }
      })
    },
    onConfirmStatus (type, id) {
      upDown({ id: id, type: type }).then(res => {
        if (res.code === 0) {
          this.refresh()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onDelete (id) {
      this.$confirm({
        title: '是否确认删除？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          const hide = this.$message.loading('删除中...')
          pageDel({ id: id }).then(res => {
            hide()
            if (res.code === 0) {
              this.refresh()
              this.$message.success(res.msg)
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.search-item {
  margin-left: 10px;
}
</style>
